import { create } from 'zustand';
import * as Tone from 'tone';
import audioAnalyzerService from '../services/audioAnalyzerService';

const useGameStore = create((set, get) => ({
  // 游戏状态
  gameStatus: 'idle',
  score: 0,
  combo: 0,
  maxCombo: 0,
  
  // 音频相关
  audioPlayer: null,
  currentTime: 0,
  songDuration: 0,
  
  // 音符相关
  activeNotes: [],
  hitNotes: [],
  
  // 玩家输入历史
  keyPresses: {},
  
  // 特效状态
  effectsQueue: [],
  
  // 初始化游戏
  initGame: () => {
    set({ 
      gameStatus: 'idle',
      activeNotes: [],
      hitNotes: [],
      score: 0,
      combo: 0,
      maxCombo: 0,
      songDuration: 0
    });
  },
  
  // 准备游戏（需要用户交互）
  prepareGame: async () => {
    set({ gameStatus: 'loading' });
    
    try {
      await Tone.start();
      
      return new Promise((resolve, reject) => {
        const player = new Tone.Player({
          url: '/audio/test-song.mp3',
          onload: () => {
            const duration = player.buffer.duration;
            console.log('音乐长度:', duration, '秒');
            
            // 生成覆盖整个音乐长度的音符
            const notesPerSecond = 2; // 每秒2个音符
            const totalNotes = Math.floor(duration * notesPerSecond);
            const testNotes = Array.from({ length: totalNotes }, (_, i) => {
              const time = i * (1 / notesPerSecond); // 均匀分布音符
              const lane = Math.floor(Math.random() * 4);
              const key = ['q', 'w', 'e', 'r'][Math.floor(Math.random() * 4)];
              
              // 根据轨道计算固定位置
              const lanePositions = [-6, -2, 2, 6];
              const x = lanePositions[lane];
              const y = 0.1; // 音符高度
              const z = -time * 20; // 根据时间计算z轴位置，速度系数为20
              
              return {
                time,
                lane,
                key,
                position: [x, y, z]
              };
            });
            
            set({ 
              audioPlayer: player,
              gameStatus: 'ready',
              songDuration: duration,
              activeNotes: testNotes
            });
            resolve();
          },
          onerror: (error) => {
            console.error('加载音频失败:', error);
            set({ gameStatus: 'error' });
            reject(error);
          }
        }).toDestination();
      });
      
    } catch (error) {
      console.error('初始化游戏失败:', error);
      set({ gameStatus: 'error' });
      throw error;
    }
  },
  
  // 开始游戏
  startGame: () => {
    const { audioPlayer, gameStatus } = get();
    if (audioPlayer && gameStatus === 'ready') {
      audioPlayer.start();
      set({ gameStatus: 'playing' });
    }
  },
  
  // 暂停游戏
  pauseGame: () => {
    const { audioPlayer, gameStatus } = get();
    if (audioPlayer && gameStatus === 'playing') {
      audioPlayer.pause();
      set({ gameStatus: 'paused' });
    }
  },
  
  // 继续游戏
  resumeGame: () => {
    const { audioPlayer, gameStatus } = get();
    if (audioPlayer && gameStatus === 'paused') {
      audioPlayer.start();
      set({ gameStatus: 'playing' });
    }
  },
  
  // 重置游戏
  resetGame: () => {
    const { audioPlayer } = get();
    if (audioPlayer) {
      audioPlayer.stop();
    }
    set({
      gameStatus: 'idle',
      hitNotes: [],
      currentTime: 0
    });
  },
  
  // 记录击中的音符
  hitNote: (note) => {
    set(state => ({
      hitNotes: [...state.hitNotes, note]
    }));
  },
  
  // 更新当前时间
  updateTime: (time) => {
    set({ currentTime: time });
  },
  
  // 处理玩家按键
  handleKeyPress: (key, isPressed) => {
    const { gameStatus, activeNotes, hitNotes, score, combo, maxCombo, keyPresses } = get();
    
    if (gameStatus !== 'playing') return;
    
    const newKeyPresses = { ...keyPresses };
    newKeyPresses[key] = isPressed;
    
    if (isPressed) {
      const currentTime = audioAnalyzerService.currentTime;
      const matchingNoteIndex = activeNotes.findIndex(note => 
        note.key === key && 
        Math.abs(note.time - currentTime) < 0.2 &&
        !hitNotes.includes(note)
      );
      
      if (matchingNoteIndex !== -1) {
        const matchingNote = activeNotes[matchingNoteIndex];
        const accuracy = 1 - Math.abs(matchingNote.time - currentTime) / 0.2;
        const newHitNotes = [...hitNotes, matchingNote];
        const newCombo = combo + 1;
        const newMaxCombo = Math.max(maxCombo, newCombo);
        const newScore = score + Math.floor(100 * accuracy) * (1 + newCombo * 0.1);
        
        const effectsQueue = [...get().effectsQueue];
        effectsQueue.push({
          type: 'hit',
          time: matchingNote.time,
          position: matchingNote.lane,
          key: key,
          accuracy,
          combo: newCombo
        });
        
        set({ 
          hitNotes: newHitNotes,
          score: newScore,
          combo: newCombo,
          maxCombo: newMaxCombo,
          effectsQueue
        });
      } else {
        set({ 
          combo: 0,
          effectsQueue: [...get().effectsQueue, {
            type: 'miss',
            time: Date.now() / 1000,
            key: key
          }]
        });
      }
    }
    
    set({ keyPresses: newKeyPresses });
  },
  
  // 处理特效队列
  processEffects: () => {
    const { effectsQueue } = get();
    const now = Date.now();
    const filteredEffects = effectsQueue.filter(
      effect => now - effect.time < 3000
    );
    
    if (filteredEffects.length !== effectsQueue.length) {
      set({ effectsQueue: filteredEffects });
    }
  }
}));

export default useGameStore; 